import router from '@/router'
import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'
import { getTimeStamp } from './auth'
const TimeOut = 3600
// 1.创建axios实例对象
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// 2.创建请求拦截
service.interceptors.request.use(config => {
  if (store.getters.token) {
    if (timeOut()) {
      store.dispatch('user/logout')
      router.push('/login')
      return Promise.reject(new Error('tolen超时了'))
    }
    config.headers['Authorization'] = `Bearer ${store.getters.token}`
  }
  return config
})

// 3.创建响应拦截
service.interceptors.response.use(res => {
  const { success, message, data } = res.data
  if (success) {
    return data
  } else {
    // alert('登录失败')
    Message(message)
    return Promise.reject(message)
  }
})

function timeOut() {
  var currentTime = Date.now() // 当前时间戳
  var timeStamp = getTimeStamp() // 缓存时间戳
  return (currentTime - timeStamp) / 1000 > TimeOut
}

// 4.导出axios实例
export default service
